﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication.Utils
{
    public class Model<T>
    {

        private bool SetModelValue(string FieldName, string Value, T o)
        {
            try
            {
                Type Ts = o.GetType();
                Type type = Ts.GetProperty(FieldName).PropertyType;
                object v = Convert.ChangeType(Value, type);
                Ts.GetProperty(FieldName).SetValue(o, v, null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public T GetModel(System.Collections.Specialized.NameValueCollection form)
        {
            T obj = System.Activator.CreateInstance<T>();

            for (int i = 0; i < form.Count; i++)
            {
                string key = form.Keys[i].ToString();
                string value = form[i].ToString();
                key = key.Substring(0, 1).ToUpper() + key.Substring(1);
                if (key == "Action") continue;
                SetModelValue(key, value, obj);
            }
            return obj;
        }

    }
}